package cn.wolfcode.p2p.base.interceptor;

import cn.wolfcode.p2p.anno.NeedLogin;
import cn.wolfcode.p2p.util.UserContext;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//前端登陆拦截器
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取处理方法对象
        if(handler instanceof HandlerMethod){
            boolean hasAnno = ((HandlerMethod)handler).hasMethodAnnotation(NeedLogin.class);
            //判断该方法对象上是否贴有NeedLogin注解
            //如果有,判断该用户是否已经登陆
            if(hasAnno && UserContext.getLoginInfo() == null){
                response.sendRedirect("/login.html");
                return false;
            }

        }
        //其他情况放行
        return true;
    }
}
